package com.yanqu.road.dao.impl;

import com.yanqu.road.dao.cache.SqlCacheParam;
import com.yanqu.road.dao.cache.SqlCachePool;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

public class TempNoPoolCacheDao extends TempNoPoolDao {

    protected SqlCacheParam getCacheParam(String sql) {
        return new SqlCacheParam(sql);
    }

    protected Object getCacheResult(SqlCacheParam param) {
        return SqlCachePool.getResult(param);
    }

    protected void addCacheResult(SqlCacheParam param, Object resultObj) {
        SqlCachePool.addResult(param, resultObj);
    }

    protected CallableStatement createCall(SqlCacheParam param) throws SQLException {
        CallableStatement call = super.getConnection().prepareCall(param.getSql());
        List<Class> typeList = param.getTypeList();
        List<Object> valueList = param.getValueList();
        for (int i = 0; i < typeList.size(); i++) {
            setParam(call, i, typeList.get(i), valueList.get(i));
        }
        return call;
    }

    private void setParam(CallableStatement call, int index, Class type, Object value) throws SQLException {
        int paramIndex = index + 1;
        if (type == Integer.class) {
            call.setInt(paramIndex, (int) value);
        } else if (type == Long.class) {
            call.setLong(paramIndex, (long) value);
        } else if (type == String.class) {
            call.setString(paramIndex, (String) value);
        } else if (type == Timestamp.class) {
            call.setTimestamp(paramIndex, (Timestamp) value);
        } else {
            throw new RuntimeException("不支持这个类型，手动在这边添加一下");
        }
    }

    // ------------------------------------------------

    public TempNoPoolCacheDao(String dbParam) {
        super(dbParam);
    }

    @Override
    public synchronized Connection getConnection() {
        throw new RuntimeException("用createCall生成");
    }

}
